<?php
require_once 'Junction/Db/Adapter.php';
require_once 'Junction/Db/Service.php';
require_once 'Junction/Utils/Config.php';
require_once 'Junction/Utils/Reflection.php';

class Junction_Db_Factory {

	/**
	 * @return Junction_Db_Service
	 */
	public static function construct() {
		try {
			$config = Junction_Utils_Config::getSingleton();

			self::loadClass($config->read('service'));
			self::loadClass($config->read('adapter'));

			$adapter = Junction_Utils_Reflection::getInstance($config->read('adapter'), array());
			$adapter->connectTo(array('db_driver' => $config->read('db_driver'),
						'db_host' => $config->read('db_host'),
						'db_name' => $config->read('db_name'),
						'db_user' => $config->read('db_user'),
						'db_pass' => $config->read('db_pass')));

			$service = Junction_Utils_Reflection::getInstance($config->read('service'),
						array());
			$service->connect($adapter);
			return $service;
		} catch (Junction_Utils_Reflection_Exception $e) {
			throw new Junction_Db_Exception($e->getMessage());
		}
	}

	private static function loadClass($service) {
		$file = str_replace('_', DIRECTORY_SEPARATOR, $service);
		$file .= '.php';
		require_once($file);
	}
}
?>